/**
 * Created by jia on 2015/6/12.
 */
//inside lib
var fs = require('fs')
var http = require('http')
var urllib = require('url')
// outside lib
var jsdom = require('jsdom')
var reqlib = require('request')

var connect = require('connect')
var redis = require('redis')

// js
var jquery = fs.readFileSync('../client/js/jquery-2.1.3.min.js', "utf-8")
var server_json = JSON.parse(fs.readFileSync('../server.json'))
redis_cli = redis.createClient(server_json['redis']['port'], server_json['redis']['host']);

function ele_me_parse(req, res, spider_url){
    var sprider_json_url = spider_url+'/userinfo'

    reqlib(sprider_json_url, function(err, response, body){
        if(!err && response.statusCode==200){
            var url_data = {}
            var userinfo = JSON.parse(body)
            url_data['least_deliver'] = userinfo['data']['deliverAmount']
            jsdom.env({
                url: spider_url,
                src: [jquery],
                done: function(error, window){
                    if(error){
                        throw error;
                    }
                    var $ = window.$

                    $('#rst_aside ul li i').each(function(){
                        if ($(this).text() == '减'){

                            var discount_text = $(this).parent().text()
                            var discount_str_list = discount_text.split('，')
                            var discount_list = []
                            for(var i =0; i != discount_str_list.length; ++i) {
                                discount_str_list[i] = discount_str_list[i].split(/[^\d]+/ig).slice(1,3)
                                if(discount_str_list[i][1] != ""){
                                    discount_list.push([Number(discount_str_list[i][0]), Number(discount_str_list[i][1])])
                                }
                            }
                            discount_list.sort(function(a,b) {return b[1] - a[1]})
                            url_data['discount'] = discount_list
                        }
                    })
                    url_data['shop_name'] = $('.rst-name').text()
                    console.log(JSON.stringify(url_data))
                    redis_cli.hset('ele-shops', spider_url, JSON.stringify(url_data))
                    res.end('yes')
                }
            })
        }
    })
}

function baidu_parse(req, res, spider_url){

    jsdom.env({
        url: spider_url,
        src: [jquery],
        done: function(error, window){
            if(error){
                throw error;
            }
            var $ = window.$
            var url_data = {}

            url_data['least_deliver'] = Number($(".main .basicinfo .b-price .b-value .b-num").text())

            var discount_text = $('#premium-notice .jian-li .reduce-msg').text()
            var discount_str_list = discount_text.split(',')
            var discount_list = []
            for(var i =0; i != discount_str_list.length; ++i) {
                discount_str_list[i] = discount_str_list[i].split(/[^\d]+/ig).slice(1,3)
                if(discount_str_list[i][1] != ""){
                    discount_list.push([Number(discount_str_list[i][0]), Number(discount_str_list[i][1])])
                }

            }
            discount_list.sort(function(a,b) {return b[1] - a[1]})

            url_data['discount'] = discount_list
            url_data['shop_name'] = $('.one-line h2').text()
            url_data['cost'] = Number($('.b-cost .b-num').text())
            console.log(JSON.stringify(url_data))
            redis_cli.hset('ele-shops', spider_url, JSON.stringify(url_data))
            res.end('yes')
        }
    })
}

app = connect();
app.use('/api/js/restaurant_spider', function(req, res) {

    var url_parse = urllib.parse(req.url, true)
    console.log(url_parse)
    var spider_url = decodeURIComponent(url_parse['query']['uri'])
    console.log(spider_url)
    var uurl_parse = urllib.parse(spider_url)
    if(uurl_parse["host"] === "r.ele.me") {
        ele_me_parse(req, res, spider_url)
    }
    else if (uurl_parse["host"] === "waimai.baidu.com"){
        baidu_parse(req, res, spider_url)
    }
    else {
        res.end('no')
    }
});

http.createServer(app).listen(server_json['nodejs']['port'], '0.0.0.0')
